package myzzyl.interceptor;

import cn.hutool.core.util.StrUtil;
import context.JwtUserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import myzzyl.domain.pojo.JwtUser;
import myzzyl.properties.JwtProperties;
import myzzyl.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * 设置用户上下文拦截器
 */
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("用户上下文拦截器拦截请求, url: {}", request.getRequestURI());
        // 1. 取出 jwt
        String jwt = request.getHeader(jwtProperties.getToken());
        // 2. 解析 JWT
        if (StrUtil.isNotBlank(jwt)){
            JwtUser jwtUser = JwtUtil.parseJwtToJwtUser(jwtProperties.getSecret(), jwt);
            // 3. 存入上下文
            JwtUserContext.setUser(jwtUser);
            log.info("用户上下文设置成功, jwtUser: {}", jwtUser);
        }
        return true;
    }
}

